package cn.ym.mongodb.controller;


import cn.ym.mongodb.domain.Comment;
import cn.ym.mongodb.service.CommentService;
import cn.ym.utils.AjaxResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comment")
@Api(value = "mongodb的接口的API",description="mongodb的接口的CRUD功能")
public class CommentController {

    @Autowired
    private CommentService commentService;

    //添加或修改mongodb信息
    @PutMapping
    @ApiOperation(value = "添加+修改" )
    public AjaxResult save(@RequestBody Comment comment){
        try {
            if(comment.getId()==null){
                commentService.add(comment);
            }else {
                commentService.update(comment);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"系统异常，请稍后重试");
        }

    }

    //删除mongodb信息
    @ApiOperation(value = "通过ID删除" )
    @DeleteMapping("/{id}")
    public AjaxResult del(@PathVariable("id") String id){
        try {
            commentService.delete(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();//打印错误信息
            return  new AjaxResult(false,"网络异常，请稍后重试");
        }
    }

    //查询所有mongodb信息
    @ApiOperation(value = "查询使用mongodb" )
    @GetMapping
    public List<Comment> findAll(){
        return commentService.findAll();
    }

    //查询单个mongodb信息
    @ApiOperation(value = "通过ID查询" )
    @GetMapping("/{id}")
    public Comment findOne(@PathVariable("id") String id){
        return commentService.findOne(id);
    }


    //查询单个mongodb信息
    @ApiOperation(value = "通过ID查询" )
    @PostMapping ("/{id}")
    public List<Comment> findByArticleId(@PathVariable("id") Long articleId){
        return commentService.findByArticleId(articleId);
    }



}